<?php 
	session_start();
	/* This file is used to keep all the major functions */ 
	
	/*
	Info: This file is used to keep all the major functions
	Author: Pritam Pebam & Sandipan
	Version: 1.0
	Contact: ptamzz@gmail.com; @ptamzz
	URL: http://12bubbles.com
	*/
	
	
	require_once('settings.php');
	require_once('qrcode.php');
	require_once('conn.php');
	
	//To Check whether a user is logged in or not
	function is_logged_in(){ if($_SESSION['login']){ return TRUE; } else  { return FALSE; } }

	//For usertracking inserting
	function usertracking(){
		$ip = $_SERVER['REMOTE_ADDR'];
		$uid = $_SESSION['userId'];
		$time = time('now');
		if(is_logged_in()) { $succ = 'Y'; } else{ $succ = 'N'; }
	    mysql_query("INSERT INTO usertracking (ipaddress,userid,time,successflag) VALUES ('".$ip."',".$uid.",".$time.",'".$succ."')");
	}
	
	// TO protect SQL Injection
	function mysql_prep($value){
		$magic_quotes_active = get_magic_quotes_gpc();
		$new_enough_php = function_exists("mysql_real_escape_string"); //i.e. PHP>=v4.3.0
		
		if($new_enough_php) { //i.e. PHP>=v4.3.0
			//Undo magic quotes, instead using mysql_real_escape_string
			if($magic_quotes_active){ $value = stripslashes($value);}
			$value = mysql_real_escape_string($value);
		} else { //older version, i.e. PHP<v4.3.0
				//if magic quotes aren't already on, then add slashes manually
				if(!$magic_quotes_active) { $value = addslashes($value);}
				//if magic quotes are active, then the slashes alreeady exist
		}
		return $value;
	}

	// Just some function to make redirection Syntax easy to remember
	function redirect_to($location = NULL) {
		if($location != NULL) {
			header("Location: {$location}");
			exit;
		}
	}
	
	//Function as the name suggest!!
	function getnewuserid(){
		$userId = 1;
		$query = mysql_query("select max(userid) as uid from users");
		while($row = mysql_fetch_array($query)) {
			$userId = $row['uid'];
			$userId++;
		}
		return $userId;
	}
	
	//Function as the name suggest!!
	function getnewstoryid(){
		$storyid = 1;
		$query = mysql_query("select max(storyid) as sid from story");
		while($row = mysql_fetch_array($query)) {
			$storyid = $row['sid'];
			$storyid++;
		}
		return $storyid;
	}
	
	//Function as the name suggest!!
	function getnewstorylineid($sid){
		$storyid = 1;
		$query = mysql_query("select max(storylineid) as sid from storyline where storyid = '{$sid}'");
		while($row = mysql_fetch_array($query)) {
			$storyid = $row['sid'];
			$storyid++;
		}
		return $storyid;
	}
	
	//Function as the name suggest!!
	function getnewentryid($sid){
		$entryid = 1;
		$slid = getnewstorylineid($sid);
		$query = mysql_query("select max(entrylineid) as eid from entryline where storyid = '{$sid}' and storylineid = '{$slid}'");
		while($row = mysql_fetch_array($query)) {
			$entryid = $row['eid'];
			$entryid++;
		}
		return $entryid;
	}
	
	//Generate Random String Function
	function genRandomString($length) {
		//if($length){ $length = 10; }
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$string = '';    
		for ($p = 0; $p < $length; $p++) {
			$string .= $characters[mt_rand(0, strlen($characters))];
		}
		return $string;
	}

	//Detect IE function
	function detectIE()	{
		if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
		return true;
		else
		return false;
	}

	//Time display function
	function timeago($time){
		$time = strtotime($time);
		$tnow = time('now');
		$timediff = $tnow-$time;
		
		if($timediff > 31104000){ // code for yrs
		$show = floor($timediff/31104000);
			if($show > 1){
				$show = 'about '.$show.' years ago';
			} else{
				$show = 'about '.$show.' year ago';
			}
		} else if($timediff > 2592000){ // code ofr months
			$show = floor($timediff/2592000);
			if($show > 1){
				$show = 'about '.$show.' months ago';
			} else{
				$show = 'about '.$show.' month ago';
			}
		} else if($timediff > 86400) {  // code for days
			$show = floor($timediff/86400);
			if($show > 1) {
				$show = 'about '.$show.' days ago';
			} else{
				$show = 'about '.$show.' day ago';
			}
		} else if($timediff > 3600){ // coed for hrs
			$show = floor($timediff/(3600));
			if($show > 1) {
				$show = 'about '.$show.' hours ago';
			} else{
				$show = 'about '.$show.' hour ago';
			}
		} else if($timediff > 60) { // code for months
			$show = floor($timediff/(60));
			if($show > 1) {
				$show = 'about '.$show.' minutes ago';
			} else{
				$show = 'about '.$show.' minute ago';
			}
		} else {
			$show = 'about few seconds ago';
		}
		return $show;
	}
	
	/* grab stuff */
	function get_posts($start = 0, $number_of_posts = 5, $storyId) {
		/* connect to the db */
		$connection = mysql_connect('localhost','root','');
		mysql_select_db('story',$connection);
		$posts = array();
		/* get the posts */
		$query = "SELECT serial, line, postedby, FROM storybody WHERE id = {$storyId} ORDER BY serial DESC LIMIT $start,$number_of_posts";
		$result = mysql_query($query);
		echo $query;
		while($row = mysql_fetch_array($result)) {
			$posts[] = $row['line'];
		}
		/* return the posts in the JSON format */
		return json_encode($posts);
	}
	
	function getPost($num, $cat) {
		include('conn.php');
		$markup = "";
		
		//Is activation link is valid, then set flag to 1
		$query = "SELECT distinct story.storyid,story.storyname from entrylinevote join story on story.storyid = entrylinevote.storyid order by (select count(entrylinevote.storyid) from entrylinevote) DESC LIMIT {$num}";
		$result = mysql_query( $query, $connection);
		if(!$result) {
			die("1:003 " . mysql_error());
		} else {
			while(($row = mysql_fetch_array($result))) {
				if(strlen($row['storyname']) > 25) {
					$continue = '...';
				} else {
					$continue = '';
				}
				$markup .= "<li><a href='index.php?page=story&id={$row['storyid']}&title=" . getStoryTitle($storyid) . "'>/" . substr($row['storyname'], 0, 25) . $continue."</a></li>";
			}
        }
		echo $markup;
	}
	
	function searchStory($name) {
		$name = strtoupper($name);
		$searchresult = '';
		$dbPath = '';
		$uname = '';
		$query = "SELECT * FROM story WHERE delflag = 'N' and UPPER(storyname) LIKE '%{$name}%'";
		$result = mysql_query($query);
		while($row = mysql_fetch_array($result)) {
			$qry = mysql_query("SELECT crtdbyid FROM story WHERE storyid = {$row['storyid']} LIMIT 1");
			
			$rowset = mysql_fetch_array($qry);
			$dpPath = userimage($rowset['crtdbyid'],'small');
			$uname = getUsername($rowset['crtdbyid']);
				
			$query1 = "select count(storyid) as cnt, storyline from storyline where storyid = {$row['storyid']} GRoup BY storyid";
			$result1 = mysql_query($query1);
			while($row1 = mysql_fetch_array($result1)) {
			
				$stringLine = ($row1['cnt'] > 1 ? 'Lines' : 'Line');
				$searchresult .= "<li class='res-line' >
									<div class='r-s left'>
										<h1><a href='index.php?page=story&id=".$row['storyid']. "&title=" . getStoryTitle($row['storyid']) . "'>".$row['storyname']."</a></h1>
										<div class='searchLine'>{$row1['storyline']}</div>
										<div class='clear'></div>
										<div class='microInfo'>{$row1['cnt']} {$stringLine}</div>
									</div>
									<div class='r-a left'>
										<a href='index.php?page=" . strtolower(getUsername($rowset['crtdbyid'])) . "'><img src='{$dpPath}'class='left avatar' style='margin-right: 10px; width: 40px;'/></a>
										<div class='microInfo left'>Last Posted by</div>
										<a href='index.php?page=" . strtolower(getUsername($rowset['crtdbyid'])) . "'><div class='nameSearch left'>".$uname."</div></a>
									</div>
									<div class='clear'></div>
								</li>";
			}
		}
		if($searchresult == '') {
			$searchresult .= "<li class='each-line'>No such story found</li>";
		}
		return $searchresult;
	}
	
	//Function as the name suggest!!
	function getrecentstory($num, $cat) {
		include('conn.php');
		$markup = "";
		
		//Is activation link is valid, then set flag to 1
		$query = "SELECT distinct storyid,storyname from story ORDER BY crtdtime DESC LIMIT {$num}";
		$result = mysql_query( $query, $connection);
		if($result) {
			while(($row = mysql_fetch_array($result))) {
				if(strlen($row['storyname']) > 25) {
					$continue = '...';
				} else{
					$continue = '';
				}
				$markup .= "<li><a href='index.php?page=story&id={$row['storyid']}&title=" . getStoryTitle($storyid) . "'>" . substr($row['storyname'], 0, 25) . $continue."</a></li>";
			}
        }
		echo $markup;
	}
	
	//Prints out entry-line submission form
	function getEntryForm($storyId, $lineId){
		$btnAction = "addline";
		$value = "Post New Line";
		$sline = '';
		$show = 'post-btn';
		if(isset($_SESSION['sline'])) {
			$sline = $_SESSION['sline'];
			unset($_SESSION['sline']);
			$show = 'post-btn1';
		}
		
		$dpPath = userimage($_SESSION['userId'],'small');
		$uname = getUsername($_SESSION['userId']);
		$credits = userlabel($_SESSION['userId']);
		$newStoryId = getnewstorylineid($storyId);

		$lineId++;
		$markup = "<li id='entryForm' class='eachLine' data-id='{$newStoryId}'> 
						<div class='strMta left'>{$newStoryId}</div> 
						<div class='strLine left'>
							<form id='addForm' class='newline' method='POST'>
								<textarea id='newline' name='newline' cols='' rows='' placeholder='Submit your next twist.' class='elastic oneSixty'>{$sline}</textarea>
								<input id='lineId' name='lineId' type='hidden' value='{$lineId}'/>
								<input id='storyId' name='storyId' type='hidden' value='{$storyId}'/>
								<img id='loadNewLine' class='hide' src='img/ajaxLoader.gif' style='position: relative; right: 5px;' />
								<input id='{$btnAction}' class='submitEL right btnB limitBtn {$show}' type='button' value='{$value}' {$show} />
							</form>
							<div class='clear'></div>
						</div>";
						
		if(is_logged_in()){			
			$markup .= "<div class='strInfo left'> 
							<a href='index.php?page=" . strtolower(getUsername($_SESSION['userId'])) . "' class='avatar'><img src='{$dpPath}' width='40' height='40' /></a> 
							<a href='index.php?page=" . strtolower(getUsername($_SESSION['userId'])) . "' class='username'><span class='left'>{$uname}</span></a> 
							<div class='rep left'> 
								<span class='bronze'></span><span class='credits'>{$credits}</span> 
							</div> 
						</div>";
		}

		$markup .= 		"<div class='clear'></div> 
					</li>";
		return $markup;
	}
	


	//getentrylinetime($args['uniqueid'])  in getentryline function
	function getentrylinetime($uniqueid){
		include('conn.php');
		$query = "SELECT crtdtime FROM entryline WHERE displayseq = {$uniqueid} AND delflag = 'N'";
		$result = mysql_query($query);
		while($row = mysql_fetch_array($result)){
			$time = $row['crtdtime'];
		}
		return $time;
	}

	//getlinetime($serial)  in getline function
	function getlinetime($uniqueid){
		include('conn.php');
		$query = "SELECT crtdtime FROM storyline WHERE storylineid = {$uniqueid} AND delflag = 'N'";
		$result = mysql_query($query);
		while($row = mysql_fetch_array($result)) {
			$time = $row['crtdtime'];
		}
		return $time;
	}

	function getstorylinetime($uniqueid){
		include('conn.php');
		$query = "SELECT crtdtime FROM storyline WHERE storylineid = {$uniqueid} AND storyid = {$_SESSION['sid']} AND delflag = 'N'";
		$result = mysql_query($query);
		while($row = mysql_fetch_array($result)) {
			$time = $row['crtdtime'];
		}
		return $time;
	}
	
	//Get user credits
	function numberofstoryline($userid){
        include('conn.php');
        $return = 0;
        $query = "select count(storyid) as num from storyline where crtdbyid = {$userid} and storylineid != 1 and delflag = 'N'";
        $result = mysql_query($query);
        while($row = mysql_fetch_array($result)) { $return = $row['num']; }
        return $return;
    }


	//Printing out each line
	function getLine($storyId, $serial, $line, $user){
		include('conn.php');
		
		$serial = $serial;
		$line = $line;
		$userId = $user;
		$credits = userlabel($args['user']);
		
		$query = "SELECT * FROM `users` WHERE `userid` = {$userId} and `delete flag` = 'N'  LIMIT 1";
		$result = mysql_query($query, $connection);
		
		while($row = mysql_fetch_array($result)) {
			$user = $row['username'];
		}
		$rep = array("\n","\'",'\"');
		$torep = array("<br/>","'",'"');
		$line = str_replace($rep,$torep,$line);
		
		$avatarPath = userimage($userId,'small');
		
		$user = trim($user);		
		$_SESSION['stlastline'] = $serial;
		$showTime = timeago(getstorylinetime($serial));
		$markup = "<li class='eachLine' data-id='{$serial}'>
						<div class='strMta left'>{$serial}</div> 
						<div class='strLine left'>
							<p>{$line}</p>
							<div class='lineMta'>
								<div class='lineMtaItemOne hide'>
									<span class='timeagoIcon'></span>
									<abbr class='timeago' title='{$showTime}'>{$showTime}</abbr>
									<span class='showElines'>Show twists</span>
								</div>
							</div>
						</div> 
						<div class='strInfo left'> 
							<a href='index.php?page=" . strtolower(getUsername($userId)) . "' class='avatar'><img src='{$avatarPath}' width='40' height='40' alt='profile'/></a> 
							<a href='index.php?page=" . strtolower(getUsername($userId)) . "' class='username'><span class='left'>{$user}</span></a> 
							<div class='rep left'> 
								<span class='bronze'></span><span class='credits'>{$credits}</span> 
							</div> 
						</div> 
						<div class='clear'></div>
						<div class='viewEntryLines hide'>
						
							<div class='eTwistsClose'>^</div>
							<ul id='etwists' class='timeline' data-id='86'>";
		$markup .=				getold5EntryLine($storyId, $serial); //getTwistLines($storyId, $serial);			
		$markup .=			"</ul>
							<!-- <div class='eTwistsMore'>Show more</div> -->
						</div>
					</li>";
		return $markup;
    }
	
	
	function userlabel($userid) {
		$numb = numberofstoryline($userid);
		if($numb > EXPERT) {
			return SUPEREXPERTTITLE;
		} elseif($numb > SPWRITER) {
			return EXPERTTITLE;
		} elseif($numb > NEWBIE) {
			return SPWRITERTITLE;
		} else {
			return NEWBIETITLE;
		}
	}
	
	// Get entry-line
	function getEntryLine($args){
		include('conn.php');
		
		$query = "SELECT * FROM `users` WHERE `userid` = {$args['user']} and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result){ while($row = mysql_fetch_array($result)) { $user = $row['username']; } }
		$disable = '';
		if($_SESSION['userId'] != $args['user']) {
			$disable = "disabled = 'disabled'";	
			$hide = "hide";
		}
		
		$avatarPath = userimage($args['user'],'small');
		$credits = userlabel($args['user']);
		
		$showTime = timeago(getentrylinetime($args['uniqueid']));
		
		//encoding line so that it doesn't break
		$lineData = rawurlencode($args['line']);
		
		$markup = "<li id='{$args['updateNode']}' class='eachLine box'> 
						<div class='elMta left'><input id='{$args['delNode']}' value='x' data-delValue='{$args['uniqueid']}' class='del {$hide} {$args['deleter']}' name='del' type='button' {$disable} /></div> 
						<div class='el left'>
							 <p>{$args['line']}</p>
							 <input id='hiddenid{$args['count']}' value='{$args['uniqueid']}' type='hidden'/>
							<div class='elLineMta'>
								<div class='lineMtaItemOne'><span class='timeagoIcon'></span><abbr class='timeago' title='{$showTime}'>{$showTime}</abbr></div>
								<!-- <div class='lineMtaItem'><a href='#'><span class='bubbleIcon'><span class='iconText'>3 Comments</span></span></a></div> -->
								<div class='lineMtaItem'><a href='#'><span class='fbShareIcon' data-stryid='{$args['stryid']}' data-eline='{$lineData}' data-line='{$args['updateNode']}' data-uid='{$args['uniqueid']}'><span class='iconText'>Share</span></span></a></div>
								<div class='lineMtaItem'><a href='#'><span data-count='{$args['count']}' data-id='{$args['uniqueid']}' class='flagIcon'><span class='iconText'>Flag Post</span></span></a></div>
							</div>
						</div> 
						<div class='elVote left'> 
							<div class='pushUp'>
								<span id='voteUp{$args['count']}' data-count='{$args['count']}' data-vote='{$args['voteUp']}' data-uid='{$args['uniqueid']}' class='voteUpIcon {$args['upClass']}'></span>
								<input id='countUp{$args['count']}' name='voteCount' type='button' value='{$args['voteUp']}' class='showVote green'/> 
							</div> 
							<div class='clear'></div> 
							<div class='pushDwn'>
								<span id='voteDwn{$args['count']}' data-count='{$args['count']}' data-vote='{$args['voteDwn']}' data-uid='{$args['uniqueid']}' class='voteDownIcon {$args['dwnClass']}'></span>
								<input id='countDwn{$args['count']}' name='voteCount' type='button' value='{$args['voteDwn']}' class='showVote red'/> 
							</div> 
						</div>
						<div class='elInfo left'> 
							<a href='index.php?page=" . strtolower(getUsername($args['user'])) . "' class='avatar'><img src='{$avatarPath}' width='40' height='40' /></a> 
							<a href='index.php?page=" . strtolower(getUsername($args['user'])) . "' class='username'><span class='left'>{$user}</span></a> 
							<div class='rep left'> 
								<span class='bronze'></span><span class='credits'>{$credits}</span> 
							</div>
						</div> 
						<div class='clear'></div> 
					</li>";
		return $markup;
	}
	


	
	// Get more button
	function showMoreBtn($serial){
		$serial = $serial;
		$markUp = "<!-- More Button here $msg_id values is a last message id value. -->
					<div id='more" . $serial . "' class='moreBox'>
						<a href='#' class='more' id='{$serial}'>Show More Lines</a>
					</div>";
		return $markUp;
	}
	
	// Getting username
	function getUsername($usrId){
		include('conn.php');
		
		$query = "SELECT * FROM `users` WHERE `userid` = {$usrId} and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result){
			while($row = mysql_fetch_array($result)) { return $row['username']; }
		} else {
			return FALSE;
		}
		
	}
	
	// Getting username
	function getName($usrId){
		include('conn.php');
		
		$query = "SELECT * FROM `users` WHERE `userid` = {$usrId} and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result){
			while($row = mysql_fetch_array($result)) { return $row['username']; }
		} else {
			return FALSE;
		}
	}
	
	// Getting Get userid
	function getUserId($email){
		include('conn.php');
		
		$query = "SELECT `userid` FROM `users` WHERE `email` = '{$email}' and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result){
			$row = mysql_fetch_array($result);
			return $row['userid'];
		} else {
			return FALSE;
		}
	}
	
	function getUserIdFromUsername($username){
		include('conn.php');
		
		$query = "SELECT `userid` FROM `users` WHERE `username` = '{$username}' and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result){
			$row = mysql_fetch_array($result);
			return $row['userid'];
		} else {
			return FALSE;
		}
	}
	
	// Getting Email
	function getEmail($usrId){
		include('conn.php');
		
		$query = "SELECT * FROM `users` WHERE `userid` = {$usrId} and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result){
			while($row = mysql_fetch_array($result)) { return $row['email']; }
		} else {
			return FALSE;
		}
		
	}
	
	//Verify email address
	function check_email_address($email) {
		  // First, we check that there's one @ symbol, and that the lengths are right.
		  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
			// Email invalid because wrong number of characters in one section or wrong number of @ symbols.
			return false;
		  }
		  // Split it into sections to make life easier
		  $email_array = explode("@", $email);
		  $local_array = explode(".", $email_array[0]);
		  for ($i = 0; $i < sizeof($local_array); $i++) {
			if
		(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
		â†ª'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
		$local_array[$i])) {
			  return false;
			}
		  }
		  // Check if domain is IP. If not, 
		  // it should be valid domain name
		  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
			$domain_array = explode(".", $email_array[1]);
			if (sizeof($domain_array) < 2) {
				return false; // Not enough parts to domain
			}
			for ($i = 0; $i < sizeof($domain_array); $i++) {
			  if
		(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
		â†ª([A-Za-z0-9]+))$",
		$domain_array[$i])) {
				return false;
			  }
			}
		  }
		  return true;
		}
		
	function isEmailAvailable($email) {
		 include('conn.php');
		// Checking whether the email is already registered or not			
		$query = "SELECT * FROM `users` WHERE `email` = '{$email}' and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query( $query, $connection);
		
		//Getting the id (which is going to be the user Id) number of the last inserted row
		if (mysql_num_rows($result) == 1) {
			//Email already registered
			return false;
		} else {
			return true;
		}
		
	}
		
	// Changed 6/9/2011
	function addtonotification($storyid,$storylineid,$uentrylineid,$event) {
        include('conn.php');
        
        $id = $_SESSION['userId'];
        $query = "SELECT followerid FROM followme WHERE followingid = {$id} and delflag = 'N'";
        $time = time('NOW');
        $result = mysql_query($query,$connection);
		$sendNoti = array();
        if($event != 4) {
            $uid = 0;
            if( $event <2) {
				$query1 = "SELECT crtdbyid FROM entryline WHERE displayseq = {$uentrylineid}";
				$result1 = mysql_query($query1,$connection);
				while($row1 = mysql_fetch_array($result1)) {
					$querys1 = "SELECT followerid FROM followme WHERE followingid = {$row1['crtdbyid']} and delflag = 'N'";
					$time = time('NOW');
					$results1 = mysql_query($querys1,$connection);
					while($rows1 = mysql_fetch_array($results1)) {
						array_push($sendNoti,$rows1['followerid']);
						mysql_query("UPDATE notification SET delflag = 'Y' WHERE followerid = {$rows1['followerid']} AND followingid = {$row1['crtdbyid']} and storyid = {$storyid} and storylineid = {{$storylineid}} and uniqueentryid = {$uentrylineid} AND delflag = 'N'");
						if($rows1['followerid'] != $row1['crtdbyid']){
						mysql_query("INSERT INTO notification (followerid,followingid,storyid,storylineid,uniqueentryid,delflag,readflag,event,crtdtime) VALUES ({$rows1['followerid']},{$row1['crtdbyid']},{$storyid},{$storylineid},{$uentrylineid},'N','N',{$event},$time)");
						}
					}
					if(!in_array($row1['crtdbyid'], $sendNoti)){
						if($row1['crtdbyid'] != $id){
							array_push($sendNoti,$row1['crtdbyid']);
							mysql_query("INSERT INTO notification (followerid,followingid,storyid,storylineid,uniqueentryid,delflag,readflag,event,crtdtime) VALUES ({$row1['crtdbyid']},{$id},{$storyid},{$storylineid},{$uentrylineid},'N','N',{$event}, $time)");
						}
					}
					$uid = $row1['crtdbyid'];
				}
            }
            while($row = mysql_fetch_array($result)) {
                if(!in_array($row['followerid'], $sendNoti)) {
                    mysql_query("UPDATE notification SET delflag = 'Y' WHERE followerid = {$row['followerid']} AND followingid = {$id} and storyid = {$storyid} and storylineid = {{$storylineid}} and uniqueentryid = {$uentrylineid} AND delflag = 'N'");
                    if($row['followerid'] != $id){
						mysql_query("INSERT INTO notification (followerid,followingid,storyid,storylineid,uniqueentryid,delflag,readflag,event,crtdtime) VALUES ({$row['followerid']},{$id},{$storyid},{$storylineid},{$uentrylineid},'N','N',{$event},$time)");
					}
                }
            }
        } else {
            $query = "SELECT crtdbyid FROM entryline WHERE displayseq = {$uentrylineid}";
            $result = mysql_query($query,$connection);

            while($row = mysql_fetch_array($result)) {
                $querys = "SELECT followerid FROM followme WHERE followingid = {$row['crtdbyid']} and delflag = 'N'";
                $time = time('NOW');
                $results = mysql_query($querys,$connection);
                while($rows = mysql_fetch_array($results)) {
                    mysql_query("INSERT INTO notification (followerid,followingid,storyid,storylineid,uniqueentryid,delflag,readflag,event,crtdtime) VALUES ({$rows['followerid']},{$row['crtdbyid']},{$storyid},{$storylineid},{$uentrylineid},'N','N',5,$time)");
                }
                mysql_query("INSERT INTO notification (followerid,followingid,storyid,storylineid,uniqueentryid,delflag,readflag,event,crtdtime) VALUES ({$row['crtdbyid']},{$id},{$storyid},{$storylineid},{$uentrylineid},'N','N',{$event}, $time)");
            }    
        }
    }

	//Function as the name suggest!!
	function findhot($page) {
		include('conn.php');
		$a = array();
		$b = array();
		$end = STORYINPAGE;
		$start = (($page * STORYINPAGE) - STORYINPAGE);
		$query = mysql_query("SELECT storyid, count(storyid) as vote_count, count(distinct votebyuserid) as unique_user_count, count(distinct votebyuserid)+count(storyid) as hotrate from entrylinevote group by storyid order by hotrate DESC LIMIT {$start}, {$end}");
		while($row = mysql_fetch_array($query)) { $b[$row['storyid']] = $row['hotrate']; }
		
		arsort($b);
		return $b;
	}

	//Function as the name suggest!!
	function findlatest($page) {
        include('conn.php');
        $b = array();
        $end = STORYINPAGE;
        $start = (($page * STORYINPAGE) - STORYINPAGE);
        $query = mysql_query("SELECT distinct(temp.storyid) as sid, Max(temp.time_post_vote) as ltime FROM
								(
									SELECT Distinct a.storyid, Max(a.crtdtime) as time_post_vote 
									FROM entrylinevote a WHERE delflag = 'N' GROUP BY a.storyid
					
									UNION
									SELECT Distinct b.storyid, Max(b.crtdtime) as time_post_vote
									FROM story b WHERE delflag = 'N' GROUP BY b.storyid
					
									UNION
									SELECT Distinct c.storyid, Max(c.crtdtime) as time_post_vote
									FROM entryline c WHERE delflag = 'N' GROUP BY c.storyid
								) as temp
								GROUP BY temp.storyid ORDER BY ltime DESC LIMIT {$start}, {$end}");
								
        while($row = mysql_fetch_array($query)) { $b[$row['sid']] = $row['sid']; }
        return $b;
    }

	//Function to find all stories a user participates
    function userallstories($userid,$page) {
        include('conn.php');
        $end = STORYINPAGE;
        $start = (($page * STORYINPAGE) - STORYINPAGE);
        $stories = '<ul>';
            $query  = "SELECT distinct(temp.storyid) as sid, Max(temp.time_post_vote) as ltime FROM
						(
							SELECT Distinct a.storyid, Max(a.crtdtime) as time_post_vote
							FROM entrylinevote a WHERE crtdbyid = {$userid} and delflag = 'N' GROUP BY a.storyid
			
							UNION
							SELECT Distinct b.storyid, Max(b.crtdtime) as time_post_vote
							FROM story b WHERE crtdbyid = {$userid} and delflag = 'N' GROUP BY b.storyid
			
							UNION
							SELECT Distinct c.storyid, Max(c.crtdtime) as time_post_vote
							FROM entryline c WHERE crtdbyid = {$userid} and delflag = 'N' GROUP BY c.storyid
						) as temp
						GROUP BY temp.storyid ORDER BY ltime DESC LIMIT {$start}, {$end}";
            $result = mysql_query($query);
            if(mysql_num_rows($result) > 0) {
                while($row = mysql_fetch_array($result)) {
                    $query1 = "SELECT count(storyid) as slines FROM storyline WHERE storyid = {$row['sid']} AND delflag = 'N'";
            		$result1 = mysql_query($query1);
                    while($rows = mysql_fetch_array($result1)) { $slines = $rows['slines']; }
                    $query1 = mysql_query("SELECT count(storyid) as votes FROM entrylinevote WHERE storyid = {$row['sid']} AND delflag = 'N'");
                    while($rows = mysql_fetch_array($query1)) { $votes = $rows['votes']; }
          			$query1 = mysql_query("SELECT storyname as stitle FROM story WHERE storyid = {$row['sid']} AND delflag = 'N'");
                    while($rows = mysql_fetch_array($query1)) { $storyline = $rows['stitle']; }
					
					$stringLine = ($slines>1 ? 'Lines' : 'Line');
					$stringVote = ($votes>1 ? 'Likes' : 'Like');
					
					$stories .= "<li>                       
									<a href='index.php?page=story&id={$row['sid']}&title=" . getStoryTitle($row['sid']) . "'><div class='sTitle'>{$storyline}</div></a>      
									<div class='sDate'>
										<div class='lineMtaItemOne'>
											<span class='timeagoIcon'></span>
											<abbr class='timeago' title='about 11 days ago'>".date('d M Y',strtotime($row['ltime']))."</abbr>
										</div>
										<div class='lineMtaItem'><span class='linesIcon'></span><a href='#'>{$slines} {$stringLine}</a></div>
										<div class='lineMtaItem'><span class='likeIcon'></span><a href='#'>{$votes} {$stringVote}</a></div>
										<!-- <div class='lineMtaItem'><span class='dislikeIcon'></span><a href='#'>6 Dislikes</a></div> -->
										<div class='clear'></div> 
									</div>                              
								</li>";
                }		// while($row = mysql_fetch_array($result)) { ENDS
            } else {
                $stories .= '<li><span class="pro-notification">No stories to display</span></li>';
            }
        $stories .= '</ul>';
        return $stories;
    }



	 //Function to find 'my' stories
    function userspecificstories($userid,$page){
        include('conn.php');
        $end = STORYINPAGE;
        $start = (($page * STORYINPAGE) - STORYINPAGE);
        $stories = '<ul>';
            $query  = "SELECT DISTINCT a.storyid as sid, a.storyname as stitle, a.crtdtime as time FROM story a WHERE crtdbyid = {$userid} and delflag = 'N' ORDER BY time DESC LIMIT {$start}, {$end}";
            $result = mysql_query($query);
            if(mysql_num_rows($result) > 0) {
                while($row = mysql_fetch_array($result)) {
                    $query1 = "SELECT count(storyid) as slines FROM storyline WHERE storyid = {$row['sid']}";
                    $result1 = mysql_query($query1);
					
					while($rows = mysql_fetch_array($result1)) { $slines = $rows['slines']; }
					$query1 = mysql_query("SELECT count(storyid) as votes FROM entrylinevote WHERE storyid = {$row['sid']} AND delflag = 'N'");
					while($rows = mysql_fetch_array($query1)) { $votes = $rows['votes']; }
					
					$stringLine = ($slines>1 ? 'Lines' : 'Line');
					$stringVote = ($votes>1 ? 'Likes' : 'Like');
					
					$stories .= "<li> 
									<a href='index.php?page=story&id={$row['sid']}&title=" . getStoryTitle($row['sid']) . "'><div class='sTitle'>{$row['stitle']}</div></a>      
									<div class='sDate'>
										<div class='lineMtaItemOne'>
											<span class='timeagoIcon'></span>
											<abbr class='timeago'>".date('d M Y',strtotime($row['time']))."</abbr>
										</div>
										<div class='lineMtaItem'><span class='linesIcon'></span><a href='#'>{$slines} {$stringLine}</a></div>
										<div class='lineMtaItem'><span class='likeIcon'></span><a href='#'>{$votes} {$stringVote}</a></div>
										<!-- <div class='lineMtaItem'><span class='dislikeIcon'></span><a href='#'>6 Dislikes</a></div> -->
										<div class='clear'></div> 
									</div>                              
								</li>";
                }
            } else {
                $stories .= '<li><span class="pro-notification">No stories to display</span></li>';
            }
        $stories .= '</ul>';
    
        return $stories;
    }


	// Change Password
	function changeEmailPwd($userid,$email,$newpassword){
		include('constants.php');
        include('conn.php');
        $query = "SELECT * from users WHERE userid = {$userid} and `delete flag` = 'N'";
        $result = mysql_query($query);
        
        if (mysql_num_rows($result) == 1) {
            while($row = mysql_fetch_array($result)) {
                mysql_query("UPDATE users SET `delete flag` = 'Y' WHERE userid = {$userid} and `delete flag` = 'N'");
                $query = "INSERT INTO users (userid,fbuid,ttrid,lnkid,username,pwd,fname,lname,email,DOB,`profile image path`,gender,`delete flag`,`time`,Isadmin,`email varification`,sendnotify) VALUES ({$row['userid']},'{$row['fbuid']}','{$row['ttrid']}','{$row['lnkid']}','{$row['username']}','{$newpassword}','{$row['fname']}','{$row['lname']}','{$email}','{$row['DOB']}','{$row['profile image path']}','{$row['gender']}','N','{$row['time']}','{$row['Isadmin']}','{$row['email varification']}','{$row['sendnotify']}')";
            }

            $result = mysql_query($query);
            if(!$result) { 
				$return['error'] = "2"; 
			} else { 
				if(issubscribe($userid)){
					// Sending Notification
					$email = getEmail($userid);
					// subject
					$subject = "You've succesfully changed your password";
					
					// message
					$message = $emailTop; 
					$message .=	"<p>Your account password has been changed succesfully.</p><br/>";
					$message .=	"<p>If you did not perform this action, consider contacting us.</p>";
					$message .=	 $emailBottom;
					
					// Mail it
					sendMail($email, $subject, $message);
				}
				$return['error'] = "3";
			}
        } else {
            $return['error'] = "1";
        }
        return $return;
    }
	
	//Function as the name suggest!!
	function resendVerification($email){
		include('conn.php');
		$rand = genRandomString(10);
		$actLnk = DOMAIN . "?id=" . $userId . "&key=" . $rand . "&email=" . $email;
		
		// Storing activation info in db
		$query = "UPDATE `activate` SET rand = '{$rand}' WHERE email='{$email}'";
					  
		$result = mysql_query( $query, $connection);
		if(!$result) { die("Inserting Activation link info Failed: " . mysql_error()); }

		// Sending Activation link to user
			
		// subject
		$subject = 'Activation link to your story account';
		
		// message
		$message = '
					<html>
					<head>
					  <title>Comon on Board and start writing your own stories!!</title>
					</head>
					<body>
					  <p>Click on the link below to activate your account</p>
					  <table>
						<tr>
						  <a href="' . $actLnk . '">Activate now</a>
						</tr>
					  </table>
					</body>
					</html>
					';

		// Mail it
		if(sendMail($email, $subject, $message)){ return TRUE; }
	}
	
	//To check if the userid is following frendid
	function isFriend($frenId,$userId) {
		include('conn.php');
		$return = '';
		$query = "SELECT * from followme WHERE followerid = {$userId} and followingid = {$frenId} and delflag = 'N'";
		$result = mysql_query($query);
		if(mysql_num_rows($result) == 1) { return 'true'; }
	}
	
	// Function to unfollow a user
	function unfollow($followerid,$followingid) {
		include('conn.php');
		$query = "UPDATE followme SET delflag = 'Y' WHERE followerid = {$followerid} and followingid = {$followingid} and delflag = 'N'";
		$result = mysql_query($query);
		if($result) { return 'Success'; } else { return 'Fail'; }
	}

	// To get the image path of a user (only the main directory location)
	function userimagepath($userid) {
		include('conn.php');

		$query = "SELECT `time` from users WHERE userid = {$userid} AND `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query);
		
		$row = mysql_fetch_array($result);
		$time = date('MY',$row['time']);
		$imagepath = "users/".$time.'/'.$userid;
		
		return $imagepath;
	}
	
	function userimagechange($userid,$path) {   //pass the path as 'user/aug2011/33/'
		include('conn.php');
		$query = "SELECT * from users WHERE userid = {$userid} and `delete flag` = 'N'";
		$result = mysql_query($query);
		
		if (mysql_num_rows($result) == 1) {
			
			if($row['profile image path'] == 'users/defaultAvatar/' || $row['profile image path']=='' || $row['profile image path']==null) {
				while($row = mysql_fetch_array($result)) {
					mysql_query("UPDATE users SET `profile image path` = '$path' WHERE `userid` = {$userid} and `delete flag` = 'N'");
				}
				$return = "Success";
			}
		} else {
			$return = "User not found";
		}
		return $return;		
	}

	//To get the user profile image path (both small and large) 
	function userimage($userid, $type) {
		include('conn.php');
		
		$image = '';
		$query = "SELECT `profile image path` FROM `users` WHERE `userid` = {$userid} AND `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query);
		
		//Generating QR code for the user
		$qr = new qrcode();
		$qr->link("/". strtolower(getUsername($userid)));			//link qr code
		$imgSrc = $qr->get_link();

		$row = mysql_fetch_array($result);
		
		if($row['profile image path'] != NULL) {
			if($type == 'small') { 
				$dpPath = DOMAIN . '/' . $row['profile image path'].'/small.jpg';
				$image = ($row['profile image path'] == 'users/defaultAvatar/') ? $imgSrc : $dpPath;
			} elseif($type == 'large') {
				$dpPath = DOMAIN . '/' . $row['profile image path'].'/dp.jpg';
				$image = ($row['profile image path'] == 'users/defaultAvatar/') ? $imgSrc : $dpPath;
			}
		} else {
			$image = $imgSrc;
		}

		return $image;
	}
	
	//To delete/remove user profile image so that it can be set to default
	function deleteuserimage($userid) {
		include('conn.php');
		$query = "SELECT * from users WHERE userid = {$userid} and `delete flag` = 'N'";
		$result = mysql_query($query);
		
		if (mysql_num_rows($result) == 1) {
			if($row['profile image path'] != 'users/defaultAvatar/') {
				while($row = mysql_fetch_array($result)) {
					mysql_query("UPDATE users SET `profile image path` = 'users/defaultAvatar/' WHERE `userid` = {$userid} and `delete flag` = 'N'");
				}
				//Retreiving user profile qr image
				$qr = new qrcode();
				$qr->link( DOMAIN . "/". strtolower(getUsername($userid)));			//link qr code
				$return['src'] = $qr->get_link();	//img source
				$return['type'] = 1;				//Success code returned to function call
			}
		} else {
			$return['type'] = 2;					//Failure code returned to function call
		}
		return $return;
	}

	// Flag to identify if a notification is already read or not
	function readnotification($uniquenotify) {
		include('conn.php');
		$query = "UPDATE notification SET readflag = 'Y' WHERE vote = {$uniquenotify} and delflag = 'N'";
		$result = mysql_query($query);
	}
	
	//Check whether a username is available or not
	function checkavailable($name){
		include('conn.php');
		
		$query = "SELECT * FROM users WHERE username = '{$name}' AND `delete flag` = 'N' LIMIT 1";
		$result = mysql_query($query);
		if(mysql_num_rows($result) == 1){
			return FALSE;
		} else {
			if(isReserved($name)){
				return FALSE;
			} else {
				return TRUE;
			}
		}
	}
	
	//Check whether username string is under the reserved category
	function isReserved($string){
		global $connection;
		
		$query = "SELECT `id` FROM `reserve` WHERE `name` = '{$string}' AND `delflag` = '1' LIMIT 1";
		$result = mysql_query($query);
		if(mysql_num_rows($result) == 1){
			return true;		//If already reserved
		} else {
			return false;		//Not reserved
		}
	}
	
	
	//To send Bug Report Email
	function reportbug($name, $emailadd, $msg) {
		$subject = 'Next Twist: Bug report';
		// message
		$message = '<html>
						<head>
						  <title>New password for Nexttwist account!!</title>
						</head>
						<body>
						  <table>
							<tr>
							  Hi,<br/>
								'.$msg.'<br/><br/>
								'.$name.'</br>
								'.$emailadd.'
							</tr>
						  </table>
						</body>
					</html>';

			// Mail it
			if(sendMail('info@nexttwist.com', $subject, $message)) { return 'true'; } else { return 'false'; }
	}
	
	//Function to authenticate the invites
	function authenticateInvite($email,$iCode) {	
		include('conn.php');
		$query = "SELECT * FROM invites WHERE email = '{$email}' AND `icode` = '{$iCode}' LIMIT 1";
		$result = mysql_query($query);
	
		if(mysql_num_rows($result) == 1) {
			$query1 = "UPDATE invites SET `flag` = 1 WHERE email = '{$email}' AND `icode` = '{$iCode}'";
			$result = mysql_query($query1);
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	// Subscribe to notification
	function subscribe($userid){
		include('conn.php');
		$query = "update users set sendnotify = 'Y' where userid = {$userid} AND `delete flag` = 'N'";
		if(mysql_query($query)) { return true; } else { return false; }
	}
	// Unsubscribe to notification
	function unsubscribe($userid){
		include('conn.php');
		$query = "update users set sendnotify = 'N' where userid = {$userid} AND `delete flag` = 'N'";
		if(mysql_query($query)) { return true; } else { return false; }
	}
	
	// Is subscribed to notification?
	function issubscribe($userid){
		include('conn.php');
		$query = "select * from users where userid = {$userid} AND `delete flag` = 'N' AND sendnotify = 'Y'";
		$result = mysql_query($query);
		if(mysql_numrows($result) == 1){ return true; } else { return false; }
	}
	
	// Identify if a story can be deleted or no. (story with only one line can be deleted or edited)
	function checkdelete($storyid){
        include('conn.php');
        $query = "SELECT * FROM storyline WHERE storyid = {$storyid} AND delflag = 'N'";
        $result = mysql_query($query);
        if(mysql_num_rows($result) > 1) { return false; } else { return true; }
    }
	
	
	function editstory($storytitle, $storyline, $storyid){
        include('conn.php');
		$storyline = mysql_prep($storyline);
		$storytitle = mysql_prep($storytitle);
        $result = mysql_query("UPDATE story SET storyname = '{$storytitle}' WHERE storyid = {$storyid} and delflag = 'N'");
		if($result){
			$query = "UPDATE storyline SET storyline = '{$storyline}' WHERE storyid = {$storyid} and delflag = 'N' and storylineid = 1";
			$result = mysql_query($query);
			if($result){ return 1; } else { return 0; }
		} else {
			return 2;
		}
    }
	
	//Get the first line of the story 
	function getFirstLine($storyid){
        include('conn.php');
        $result = mysql_query("SELECT * FROM storyline WHERE storyid = {$storyid} AND storylineid = 1 AND delflag = 'N'");
		if($result){
			while($row = mysql_fetch_array($result)){ $line = $row['storyline']; }
		} 
		return $line;		
    }
    
	//Delete a story
    function deletestory($storyid) {
        include('conn.php');
        $res1= mysql_query("UPDATE story SET delflag = 'Y' WHERE storyid = {$storyid} and delflag = 'N'");
        $res2= mysql_query("UPDATE storyline SET delflag = 'Y' WHERE storyid = {$storyid} and delflag = 'N'");
		$res3= mysql_query("UPDATE entryline SET delflag = 'Y' WHERE storyid = {$storyid} and delflag = 'N'");
		$res4= mysql_query("UPDATE entrylinevote SET delflag = 'Y' WHERE storyid = {$storyid} and delflag = 'N'");
		$res5= mysql_query("UPDATE notification SET delflag = 'Y' WHERE storyid = {$storyid} and delflag = 'N'");
		
		if($res1 && $res2 && $res3 && $res4 && $res5){ return true; } else { return false; }
    }
	
	//To find who started a story 
	function storyuser($storyid) {
		include('conn.php');
		$query = mysql_query("select crtdbyid from story where storyid = {$storyid} and delflag = 'N'");
		while($row = mysql_fetch_array($query)){ $user = $row['crtdbyid']; }
		return $user;
    }
	
	//Remember Me cookie function
	function insertCookie($uid, $identifier, $token){
		include('conn.php');
		$query = "INSERT INTO `remember` (userid, identifier, token, flag, time) VALUES ({$uid}, '{$identifier}', '{$token}', 'N', NOW())";
		if(mysql_query($query)) { return true; } else { return false; }
	}
	
	function updateCookie($uid, $identifier, $token){
		include('conn.php');
		$query = "UPDATE `remember` SET `flag` = 'Y' WHERE `userid` = {$uid} AND `identifier` =  '{$identifier}'";
		if(mysql_query($query)) {
			if(insertCookie($uid, $identifier, $token)) { return true; } else { return false; }
		} else {
			return false; 
		}
	}
	
	function authenticateCookie($uid,$identifier, $token){
		include('conn.php');
		$query = "SELECT * FROM `remember` WHERE `userid` = {$uid} AND `identifier` = '{$identifier}' AND `token` = '{$token}' AND `flag` = 'N' LIMIT 1";
		$result = mysql_query($query) or die("Login Failed: " . mysql_error());
		
		if(mysql_num_rows($result) == 1){ 
			return true;
		} else {
			return false;
		}
	}
	
	//this function is used to search the users
	function searchUser($name) {
		$name = strtoupper($name);
		$searchresult = '';
		$dbPath = '';
		$uname = '';
		$query = "SELECT `userid`, `username` FROM users WHERE `delete flag` = 'N' and UPPER(username) LIKE '%{$name}%'";
		$result = mysql_query($query);	
		$return = "<ul>";
		$i = 0;
		while($row = mysql_fetch_array($result)) {
			$path = userimage($row['userid'],'small');
			$username = $row['username'];
			
			$return .= "<li class='fList' style='width: 80px; float: left; margin-right: 10px; text-align: center;' >
							<img src='{$path}' style='width: 40px; margin: 0 auto; text-align: center; margin-bottom: 5px;'>
							<div><a href='/" . strtolower(getUsername($row['userid'])) . "'>$username</a></div>
						</li>";
			$i++;
		}
		$return .= "</ul>";
		
		if ($i == 0 ){ $markup = "<ul><li>There is no user with this name.</li></ul>"; } else { $markup = $return; }
	
		return $markup;
	}
	
//Crop profile image (check same function at singleImgLoad.php if it is needed there)
function crop($filename, $dst, $new_width, $new_height){
	list($width, $height) = getimagesize($filename);					//get width and height
	$imgInfo = getimagesize($filename);									//get mime type
	$mime_type=$imgInfo['mime'];
	$image_p = imagecreatetruecolor($new_width, $new_height);			//destination image
	
	if($mime_type=="image/jpeg")										//set proper mime type for destination
		$image = imagecreatefromjpeg($filename);
	elseif($mime_type=="image/png")
		$image = imagecreatefrompng($filename);
	elseif($mime_type=="image/gif")
		$image = imagecreatefromgif($filename);
		
	//resample
	if($width==$height){ imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); }			//if 1:1
	elseif($width>$height){ imagecopyresampled($image_p, $image,  0, 0, (($width-$height)/2), 0, $new_width, $new_height, $width-($width-$height), $height); }	//if width> height
	elseif($width<$height){ imagecopyresampled($image_p, $image, 0, 0, 0, (($height-$width)/2), $new_width, $new_height, $width, $height-($height-$width)); }	// if height>width
	
	// Output
	imagejpeg($image_p, $dst.".jpg", 100);		//set default type to jpg
}

//Limit num words
function string_limit_words($string, $word_limit) {
	$words = explode(' ', $string);
	return implode(' ', array_slice($words, 0, $word_limit));
}

//pass story title and convert in into SEO URL
function makeSeo($text) {
      // replace non letter or digits by -
      $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
      // trim
      $text = trim($text, '-');
      
	  // lowercase
      $text = strtolower($text);

      // remove unwanted characters
      $text = preg_replace('~[^-\w]+~', '', $text);

      if(strlen($text) > $limit) {
        $text = substr($text, 0, 70);
      } 

      if (empty($text)) {
        //return 'n-a';
        return time();
      }

      return $text;
}

//Get the story title from db and return SEO title
function getStoryTitle($storyid){
	global $connection;
	
	$query = "SELECT `storyname` FROM `story` WHERE `storyid` = {$storyid} AND `delflag` = 'N' LIMIT 1";
	$pagequery = mysql_query($query, $connection); 
	if(!$pagequery){
		$return = false;
	} else {
		$row = mysql_fetch_array($pagequery);
		$return = makeSeo($row['storyname']);
	}
	return $return;
}

function getStoryTitleNormal($storyid){
	global $connection;
	$pagequery = mysql_query("SELECT `storyname` FROM `story` WHERE `storyid` = {$storyid} AND `delflag` = 'N' LIMIT 1", $connection);
	$row = mysql_fetch_array($pagequery);
	
	return $row['storyname'];
}

	// Get old top 5 entry-line
	function getold5EntryLine($storyid, $storyLineId){
		global $connection;
		
		$markup = "";
		$msg = 0;
		//$dbquery = "select * from entryline a, v_entryline_vote_count b where a.storyid={$storyid} and  a.storyid = b.storyid and a.storylineid = {$storyLineId} and a.displayseq = b.entrylineid order by vote_count desc limit 1, 5";
		//Data is not updating in v_entryline_vote_count so removed this for now.
		$dbquery = "select * from entryline a where a.storyid={$storyid} and a.storylineid = {$storyLineId} limit 1, 5";
		$query = mysql_query($dbquery, $connection);
		
		while($rows = mysql_fetch_array($query)){
			$queryUser = "SELECT * FROM `users` WHERE `userid` = {$rows['crtdbyid']} and `delete flag` = 'N' LIMIT 1";
			$result = mysql_query($queryUser, $connection);
			if($result){ while($row = mysql_fetch_array($result)) { $user = $row['username']; } }
		
			$avatarPath = userimage($rows['crtdbyid'],'small');
			$credits = userlabel($rows['crtdbyid']);
		
			$showTime = timeago($rows['crtdtime']);
		
			//encoding line so that it doesn't break
			$lineData = rawurlencode($rows['entryline']);
			$queryup = mysql_query("SELECT count(vote) as voteup from entrylinevote WHERE storyid = '{$storyid}' and entrylineid = '{$rows['displayseq']}' and delflag = 'N' and vote = 1");
			while( $row1 = mysql_fetch_array($queryup)) { $voteup = $row1['voteup']; }
			$querydn = mysql_query("SELECT count(vote) as votedown from entrylinevote WHERE storyid = '{$storyid}' and entrylineid = '{$rows['displayseq']}' and delflag = 'N' and vote = -1");
			while( $row1 = mysql_fetch_array($querydn)) { $votedown = $row1['votedown']; }
			
			$markup .= "<li class='eachLine box'> 
							<div class='el left' style='width: 445px;'>
								 <p>{$rows['entryline']}</p>
								 <input id='hiddenid{$args['count']}' value='{$args['uniqueid']}' type='hidden'/>
								<div class='elLineMta'>
									<div class='lineMtaItemOne'><span class='timeagoIcon'></span><abbr class='timeago' title='{$showTime}'>{$showTime}</abbr></div>
								</div>
							</div> 
							<div class='elVote left' style='width: 25px;'> 
								<div class='pushUp'>
									<input name='voteCount' type='button' value='{$voteup}' class='showVote green'/> 
								</div> 
								<div class='clear'></div> 
								<div class='pushDwn'>
									<input name='voteCount' type='button' value='{$votedown}' class='showVote red'/> 
								</div> 
							</div>
							<div class='elInfo left' style='width: 45px;'> 
								<a href='index.php?page=" . strtolower(getUsername($rows['crtdbyid'])) . "' class='avatar'><img src='{$avatarPath}' width='40' height='40' /></a> 
							</div> 
							<div class='clear'></div> 
						</li>";
						
					$msg++;
						
		}
		
		if($msg == 0){
			$markup .= "<div style='min-height: 25px; text-align: center; font-size: 12px; color: #3E6AB3; padding-top: 15px;'>There are no other entries for this line.</div>";
		}
		return $markup;
	}
	
//Insert email to invitee list
function invite($inviteeEmail, $inviterId){
	//$time = time('now');
	global $connection;
	$query = "INSERT INTO `inviteelist` (email, invitedby, time, registered) VALUES ('{$inviteeEmail}', {$inviterId}, NOW(), 0)";
	$result = mysql_query($query, $connection);
	if($result){ return true; } else { return false; }
}

function isEmailInvited($inviteeEmail, $inviterId){
	global $connection;
	$query = "SELECT `id` FROM `inviteelist` WHERE `email` = '{$inviteeEmail}' AND `invitedby` = {$inviterId} LIMIT 1";
	$result = mysql_query($query, $connection);
	if($result){
		if(mysql_num_rows($result) == 1){
			return true;
		} else {
			return false;
		}
	} else { 
		return false;
	}
}

//Message

//Function as the name suggest!!
function getnewmsgid(){

	$query = mysql_query("select max(msgid) as msgid from msgtable");
	while($row = mysql_fetch_array($query)) {
		$msgid = $row['msgid'];
		$msgid++;
	}
	return $msgid;
}

/*
This function is used to send msg
input param: senderid 
input param: receiverid 
input param: massage
ouput param: boolean 
*/
function sendmsg($senderid, $receiverid, $msg){
	global $connection;
	
	//check if there is already a conversation
	$query = "SELECT `msgid` FROM  `msgtable` 
				WHERE `sendershow` = 'N' 
					AND ((`senderid` = '{$senderid}' AND `receiverid` = '{$receiverid}') OR (`senderid` = '{$receiverid}' AND `receiverid` = '{$senderid}')) 
					GROUP BY `senderid` 
					ORDER BY crtdtime desc 
					LIMIT 1";
	$result = mysql_query($query, $connection);
	
	if($result){
		if(mysql_num_rows($result) == 1){
			$row = mysql_fetch_array($result);
			$msgid = $row['msgid'];
		} else {
			$msgid = getnewmsgid();
		}
	}
	
	
	$query = "INSERT INTO `msgtable` (
				`id` ,
				`msgid`,
				`senderid` ,
				`receiverid` ,
				`msg` ,
				`sendershow` ,
				`receivershow`,
				`delflag`,
				`crtdtime`
			) VALUES (
				NULL , {$msgid}, '$senderid',  '$receiverid',  '$msg',  'N', 'N', 0, now()
			)";
	$result = mysql_query($query, $connection);
	
	if($result){
		return $msgid;
	} else {
		return false;
	}
}


/*
This function is used to show the sent messages
input param: senderid 
ouput param: String containing the messages in <li>
*/
function showsendmsg($senderid, $num){
	global $connection;

	$query = "SELECT * FROM (
				SELECT max(crtdtime) as last 
					FROM `msgtable` 
					WHERE `sendershow` = 'N' 
						AND `delflag` = 0
						AND (`senderid` = '{$senderid}' OR `receiverid` = '{$senderid}') 
						GROUP BY `msgid`
				) AS tbl
				JOIN `msgtable` o2 ON (o2.crtdtime = tbl.last)
				GROUP BY  msgid
				ORDER BY crtdtime DESC  
				LIMIT {$num}";
	
	$result = mysql_query($query);
	$messages = '';
	$cnt = 0;
	while($row = mysql_fetch_array($result)){
		//display proper user image
		if($row['receiverid'] == $senderid){
			$userid = $row['senderid'];
		} else{
			$userid = $row['receiverid'];
		}
		
		
		$queryUser = "SELECT * FROM `users` WHERE `userid` = {$userid} and `delete flag` = 'N' LIMIT 1";
		$result1 = mysql_query($queryUser, $connection);
		if($result1){ while($rows = mysql_fetch_array($result1)) { $user = $rows['username']; } }
		
		$concatenateMsg = limit_words($row['msg'], 100); //preg_replace('/\s+?(\S+)?$/', '', substr($row['msg'], 0, 100));
		
		if(strlen($row['msg'])  > 100){
			$concatenateMsg .= "...";
		}
	
		$avatarPath = userimage($userid,'small');
		$showTime = timeago($row['crtdtime']);
		$username = strtolower(getUsername($userid));
		
		$ifReply = ($row['senderid'] == $_SESSION['userId'])? "<span class='msg-reply'></span>" : "";
		
		$messages .= "<li class='eachLine box'> 
							<div class='elMta left'>{$ifReply}</div> 
							<div class='el left' style='width: 440px; margin-left: 5px;'>
								<a href='".DOMAIN."/index.php?page=message&id={$row['msgid']}' class='msg-link'>
									<p>{$concatenateMsg}</p>
									<div class='elLineMta'>
									<div class='lineMtaItemOne'>
										<span class='timeagoIcon'></span>
										<abbr class='timeago' title='{$showTime}'>{$showTime}</abbr>
									</div>
									</div>
								</a>
							</div> 
							<div class='elInfo left'> 
								<a href='index.php?page=" . strtolower(getUsername($userid)) . "' class='avatar'>
									<img src='{$avatarPath}' width='40' height='40' class='left'/>
									<span class='left' style='margin-left: 5px; font-weight: bold;'>{$username}</span>
								</a>
								<div class='clear'></div> 
							</div>
							<div class='clear'></div> 
						</li>";
					$cnt++;
	}
	if($cnt == 0){
		$messages = "<li class='eachLine box'> No message found. </li>";
	}
	return $messages;
}

function showmsgflyout($senderid, $num){
	global $connection;
	
	$query = "SELECT * FROM  `msgtable` 
				WHERE `sendershow` = 'N' 
					AND (`senderid` = '{$senderid}' OR `receiverid` = '{$senderid}')
					AND `delflag` = 0
					GROUP BY `msgid` 
					ORDER BY crtdtime DESC
					LIMIT {$num}";
	
	$result = mysql_query($query);
	$messages = '';
	$cnt = 0;
	while($row = mysql_fetch_array($result)){
		//display proper user image
		if($row['receiverid'] == $senderid){
			$userid = $row['senderid'];
		} else{
			$userid = $row['receiverid'];
		}
		
		
		$queryUser = "SELECT * FROM `users` WHERE `userid` = {$userid} and `delete flag` = 'N' LIMIT 1";
		$result1 = mysql_query($queryUser, $connection);
		if($result1){ while($rows = mysql_fetch_array($result1)) { $user = $rows['username']; } }
		
		$concatenateMsg = limit_words($row['msg'], 70); //preg_replace('/\s+?(\S+)?$/', '', substr($row['msg'], 0, 100));
		
		if(strlen($row['msg'])  > 70){
			$concatenateMsg .= "...";
		}
	
		$avatarPath = userimage($userid,'small');
		$showTime = timeago($row['crtdtime']);
		
		$username = strtolower(getUsername($userid));
		
		$messages .=	"<li class='eachNotice {$class}'>
							<a href='".DOMAIN."/index.php?page=message&id={$row['msgid']}' class='' >
								<img src='{$avatarPath}' width='40' height='40' class='left' style='margin: 0 10px 10px 0;'/>
								<div class='left' style='width: 240px;'>
									<h1>{$username}</h1>
									<p>{$concatenateMsg}</p>
								</div>
								<div class='clear'></div> 
								<div class='noticeMta'>
									<span class='timeagoIcon'></span><abbr class='timeago' title='{$showTime}'>{$showTime}</abbr>
								</div>
							</a>
						</li>";
					
					
					$cnt++;
	}
	if($cnt == 0){
		$messages = "<li class='eachLine box'> No message found. </li>";
	}
	return $messages;
}

function showConversation($msgid){
	global $connection;
	
	$messages ='';
	$query = "SELECT * FROM 
				(SELECT * FROM `msgtable` 
					WHERE `msgid` = {$msgid} 
					AND `sendershow` = 'N'
					AND `delflag` = 0
					ORDER BY `crtdtime` DESC 
					LIMIT 10) AS tbl 
				ORDER BY tbl.crtdtime";

	$result = mysql_query($query, $connection);
	while($row = mysql_fetch_array($result)){
	
		$queryUser = "SELECT * FROM `users` WHERE `userid` = {$row['senderid']} and `delete flag` = 'N' LIMIT 1";
		$result1 = mysql_query($queryUser, $connection);
		if($result1){ while($rows = mysql_fetch_array($result1)) { $user = $rows['username']; } }
		
		$avatarPath = userimage($row['senderid'],'small');
		$showTime = timeago($row['crtdtime']);
		$username = strtolower(getUsername($row['senderid']));
		
		$messages .= "<li class='eachLine box'> 
						<div class='elMta left'>";
		
		if($row['senderid'] == $_SESSION['userId']){
				$messages .=	"<input id='msgdel".$row['id']."' value='x' data-muid='{$row['id']}' class='msg-del' name='del' type='button'/>";
		}
			
		$messages .=	"</div> 
						<div class='el left' style='width: 390px; margin-right: 10px;'>
							<p>{$row['msg']}</p>
							<div class='elLineMta'>
							<div class='lineMtaItemOne'><span class='timeagoIcon'></span><abbr class='timeago' title='{$showTime}'>{$showTime}</abbr></div>
							</div>
						</div> 
						<div class='elInfo left'> 
							<a href='index.php?page=" . strtolower(getUsername($row['senderid'])) . "' class='avatar'>
								<img src='{$avatarPath}' width='40' height='40' />
							</a> 
							<a href='index.php?page=" . strtolower(getUsername($row['senderid'])) . "' class='username' style='margin-left: 5px;'>
								<span class='left'>{$username}</span>
							</a>
						</div> 
						<div class='clear'></div> 
					</li>";
					$cnt++;
		
	} //while ends
	if($cnt == 0){
		$messages = "<li class='eachLine box'> No message found. </li>";
	}
	return $messages;
}

//Find who the current user is conversing with
function conversingWith($msgid){
	global $connection;
	
	$query = "SELECT `senderid`, `receiverid` FROM `msgtable` WHERE `msgid` = {$msgid} AND `delflag` = 0 LIMIT 1";
	$result = mysql_query($query, $connection);
	if(mysql_num_rows($result) == 1){
		$row = mysql_fetch_array($result);
		
		if($row['senderid'] == $_SESSION['userId']){
			$userid = $row['receiverid'];
		} else {
			$userid = $row['senderid'];
		}
		
		$queryUser = "SELECT `username` FROM `users` WHERE `userid` = {$userid} AND `delete flag` = 'N' LIMIT 1";
		$result1 = mysql_query($queryUser, $connection);
		if($result1){ 
			$rows = mysql_fetch_array($result1);
			return $rows['username']; 
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function isMsgVisible($uid){
	global $connection;
	
	$query = "SELECT `id` FROM `msgtable` where senderid = {$uid} OR receiverid = {$uid} LIMIT 1";
	$result = mysql_query($query, $connection);
	if(mysql_num_rows($result) == 1){
		return true;
	} else {
		return false;
	}
}


function searchFriends($string){
	global $connection;
	
	$query = "SELECT `id` FROM `msgtable` where senderid = {$uid} OR receiverid = {$uid} LIMIT 1";
	$result = mysql_query($query, $connection);
	
}

function limit_words($string, $word_limit){
    $words = explode(" ",$string);
    return implode(" ",array_splice($words,0,$word_limit));
}

//Send Email using PostMark API
function sendMail($to, $subject, $body){
	$data = array(
				"From"=> "Next Twist <info@nexttwist.com>",
				"To"=> $to,
				"Subject"=> $subject,
				"HtmlBody"=> $body
			);
	$data_string = json_encode($data);
	 
	$ch = curl_init('http://api.postmarkapp.com/email');
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_string),'X-Postmark-Server-Token: ' . POSTMARK_API_KEY));
	 
	$result = curl_exec($ch);
	$resultDetails = json_decode($result);
	if($resultDetails->ErrorCode == 200 || $resultDetails->ErrorCode == 0){
		return true;
	} else{
		return false;
	}
}

//Send Notification for NT messaging system
function sendMsgNotification($receiverid, $msg, $msgId){
		$senderName = getName($_SESSION['userId']);
		$receiverName = getName($receiverid);
		$receiverEmail = getEmail($receiverid);
		$concatenateMsg = limit_words($msg, 70); // preg_replace('/\s+?(\S+)?$/', '', substr($msg, 0, 100));

		if(strlen($row['msg'])  > 100){ $concatenateMsg .= "..."; }

		$subject = "{$senderName} has sent you a message";								// subject
					
		$message = $emailTop; 															// message
		$message .=	"<p><a href='".DOMAIN."/index.php?page={$senderName}'>{$senderName}</a> has sent you a message at <a href='".DOMAIN."'>Next Twist</a>.</p>
					 <p>{$concatenateMsg}</p><br/>
					 <p><a href='".DOMAIN."/index.php?page=message&id={$msgId}'>View Full Message</a></p>";
		$message .=	 $emailBottom;

		if(sendMail($receiverEmail, $subject, $message)){ 
			return true; 
		} else { 
			return false; 
		}		// Mail it
}

?>